<?php

namespace Qwadmin\Model;

class IncomeModel extends \Think\Model{
    /**
     *  添加记录
     */
    public function add_data($data){
        return M("income")->add($data);
    }
    
    public function getList($map ,$pagesize = 20 ){
        import('ORG.Util.Page');// 导入分页类
        $income = M("view_income");
        $count = $income->where($map)->count();
        $pagebar = new \Think\Page($count, $pagesize);
        $show = $pagebar->show();
        $list = $income->where($map)->order("create_time desc")->limit($pagebar->firstRow ." ," . $pagebar->listRows)->select();
		//提取书籍ID
		$bookid_arr = [];
		$cache_booktitle = S('cache_booktitle');
        foreach($list as $key => $value){
			if(!empty($value['bookid'])){
				//当书籍缓存了标题后，将不再去查询
				if(!empty($cache_booktitle) && isset($cache_booktitle[$value['bookid']]) && !empty($cache_booktitle[$value['bookid']])){
					$list[$key]['book_title'] = $cache_booktitle[$value['bookid']];
				}else{
					$bookid_arr[$value['bookid']][] = $key;
				}
			}
		}
		//当有需要查询书籍标题内容时，去查询
		if(count($bookid_arr) > 0){
			$json = D('Novel')->get_booktitle(['book'=>implode(',',array_keys($bookid_arr))]);
			if($json != 'err'){
				$arr_data = json_decode($json, true);
				foreach($arr_data as $key => $value){
					$cache_booktitle[$key] = $value;
					foreach($bookid_arr[$key] as $val){
						$list[$val]['book_title'] = $value;
					}
				}
				S('cache_booktitle',$cache_booktitle);
			}
		}
        return [
            'list' => $list,
            'page'  => $show
        ];
    }
	/**
	* 获取账单列表
	**/
	function getbills($pram){
		$prefix = C('DB_PREFIX');
        $page = intval($pram['page']) ?  $pram['page'] : 1;         //当前分页页码
        $pageSize = intval($pram['rows']) ? $pram['rows'] : 10;     //每页显示记录数
        $where = [
            'refid' => is_array($pram['uid'])?['in',$pram['uid']]:$pram['uid'],
        ];
		if (!empty($pram['status'])) {
			$where['status']= $pram['status'];
        }
		if (!empty($pram['start_date'])) {
			$where['bills_date']= array(array('EGT', $pram['start_date']));
        }
        if (!empty($pram['end_date'])) {
			$where['bills_date'][]= array('lt', $pram['end_date']);
        }
        $order = "bills_date desc";
        
        $first = $pageSize * ($page - 1);
        $data['list']  = M('member_bills')
							->where($where)
                            ->order($order)
                            ->limit($first, $pageSize)
                            ->select();
		//echo M('member_bills')->getLastsql();
        $data["count"] = M('member_bills')->where($where)->count('id');
        return $data;
	}
	
	/**
	* 获取账单统计
	**/
	function getbills_count($pram){
		$prefix = C('DB_PREFIX');
        $where = [
            'refid' => is_array($pram['uid'])?['in',$pram['uid']]:$pram['uid']
        ];
		if (!empty($pram['start_date'])) {
			$where['bills_date']= array(array('EGT', $pram['start_date']));
        }
        if (!empty($pram['end_date'])) {
			$where['bills_date'][]= array('lt', $pram['end_date']);
        }
        $order = "bills_date desc";
        //统计总额
        $total_money  = M('member_bills')->field('sum(money) as money,sum(income) as income,sum(basic_success_num+vip_success_num) as success_num')
							->where($where)
                            ->find();
		$where['status']=1;
		$not_money = M('member_bills')->field('sum(income) as income')
							->where($where)
                            ->find();
		$where['status']=2;
		$apply_money = M('member_bills')->field('sum(income) as income')
							->where($where)
                            ->find();
		//获取登录账户的分成比例				
		$member = M('member')->field('proportion')->where(['uid'=>session('uid')])->find();					
		
		$data['total_money']= sprintf('%.2f', $total_money['money']);//总充值
		$data['total_income']= sprintf('%.2f', $total_money['income']);//总收益
		$data['success_num']= $total_money['success_num'];//充值单
		$data['apply_money']=sprintf('%.2f', $apply_money['income']);//申请中
		$data['not_money']=sprintf('%.2f', $not_money['income']);//未提现
		$data['play_money']=sprintf('%.2f', $total_money['income']-$apply_money['income']-$not_money['income']);//已打款
		$data['total_member_money']=sprintf('%.2f', $total_money['money']*($member['proportion']/100));//进账
		$data['total_member_income']=sprintf('%.2f', $total_money['money']*($member['proportion']/100)-$total_money['income']);//利润
		
        return $data;
	}
	
	/**
	* 统计用户一段时间内的总收益
	**/
	function Income_users_cont($uid,$start,$end){
		//获取代理当日的账单数据
		if((is_array($uid) && count($uid)==0) || !is_array($uid) && empty($uid)){
			return ['money'=>0,'income'=>0];
		}
		$where = [
				'refid'	=> is_array($uid)?['in',$uid]:$uid
			];
		if(!empty($start)){
			$where['bills_date'][] = [
				'EGT',
				$start
			];
		}
		if(!empty($end)){
			$where['bills_date'][] = [
				'LT',
				$end
			];
		}
		
		$bills = M('member_bills')->field('sum(money) as money,sum(income) as income')
								  ->where($where)
								  ->find();	
			
		return $bills;
	}
	/**
	* 用户多日数据统计
	**/
	function Income_muchday($uid,$start,$end){
		$cache_Income_muchday = S('Income_muchday_'.$uid.'_'.$start.'_'.$end);
		//$cache_Income_muchday =false;
		if(empty($cache_Income_muchday)){
			//获取代理当日的账单数据
			$where = [
					'refid'			=> $uid
				];
			if(!empty($start)){
				$where['bills_date'][] = [
					'EGT',
					$start
				];
			}
			if(!empty($end)){
				$where['bills_date'][] = [
					'LT',
					$end
				];
			}
			
			$bills = M('member_bills')->field('sum(money) as money,sum(vip_money) as vip_money,sum(basic_money) as basic_money,sum(vip_success_num) as vip_success_num,sum(basic_success_num) as basic_success_num,sum(vip_fail_num) as vip_fail_num,sum(basic_fail_num) as basic_fail_num,sum(vip_success_number) as vip_success_number,sum(basic_success_number) as basic_success_number,sum(reg_user) as reg_user,sum(reg_woman_user) as reg_woman_user,sum(reg_man_user) as reg_man_user,sum(subscribe) as subscribe,sum(pay_user) as pay_user')
									  ->where($where)
									  ->find();	
			
			if($start == 0){//查询总数据
				//更新为0账单的状态
				M('member_bills')->where(['money'=>0,'status'=>1,'refid'=>$uid])->save(['status'=>3]);
			}
			
			
			$time = time();
			$now_day=strtotime(date('Y-m-d'));
			if($time-$now_day<180){//凌晨3分前缓存数据只保留10秒
				$day_time = 10;
			}else{
				$day_time = 3600*24;
			}
			
			S('Income_muchday_'.$uid.'_'.$start.'_'.$end,$bills,$day_time);
		}else{
			$bills = $cache_Income_muchday;
		}
		return $bills;
	}
	/**
	* 用户今日充值统计
	**/
	function Income_today_count($uid,$level,$money=0){
		$start = strtotime(date('Y-m-d',time()));
		$end = strtotime(date('Y-m-d',strtotime('+1 day')));
		$where = [
					'refid'			=> $uid,
					'status'		=> 1,
					'deduction'		=> 1,//是否扣量 1正常
				];
		if(!empty($start)){
			$where['request_time'][] = [
				'EGT',
				$start
			];
		}
		if(!empty($end)){
			$where['request_time'][] = [
				'LT',
				$end
			];
		}
		$sel_ret = M('userrecharge')->where($where)->sum('money');
		if($level < 4){//当其级别大于二级推广商时
			$member_list = M('member')->field("uid,level,t")
				->where('pid = '.$uid)
				->order('uid desc')
				->select();
			foreach($member_list as $value){
				$member_t = strtotime(date('Y-m-d',$value['t']));//获取帐号创建日期
				if($member_t >= $end){//当日还未创建此帐号，不需要统计数据
					continue;
				}
				$sel_ret = $this->Income_today_count($value['uid'],$value['level'],$sel_ret);
			}
		}
		$money += $sel_ret;
		return $money;
	}
	/**
	* 用户收益统计
	**/
	function Income_count($uid,$level,$proportion,$start,$end,$ret=[]){
		if(count($ret)==0){
			$ret = [
					'money'					=> 0,//充值总额
					'vip_money'				=> 0,//vip充值金额
					'basic_money'			=> 0,//普通充值金额
					'vip_success_num'		=> 0,//VIP充值成功订单数
					'basic_success_num'		=> 0,//普通充值成功订单数
					'vip_fail_num'			=> 0,//VIP充值失败订单数
					'basic_fail_num'		=> 0,//普通充值失败订单数
					'vip_success_number'	=> 0,//VIP充值成功人数
					'basic_success_number'	=> 0,//普通充值成功人数
					'reg_user'				=> 0,//总注册数
					'reg_woman_user'		=> 0,//注册女性
					'reg_man_user'			=> 0,//注册男性
					'subscribe'				=> 0,//关注数
					'pay_user'				=> 0,//支付人数
			];
		}
		if($level==1){
			$proportion=100;
		}
		$cache_Income_count = S('Income_count_'.$uid.'_'.$level.'_'.$start.'_'.$end);
		//echo 'Income_count_'.$uid.'_'.$level.'_'.$start.'_'.$end;
		//var_dump($cache_Income_count);
		//$cache_Income_count=false;
		if(empty($cache_Income_count)){
			$ret_bills=$this->get_member_bills($uid,$start);
			if(!$ret_bills){//代理当日账单数据不存在 就查询
				$sel_ret = $this->Income_sel($uid,$start,$end);
				if($level < 4){//当其级别大于二级推广商时
					$member_list = M('member')->field("uid,level,proportion,t")
						->where('pid = '.$uid)
						->order('uid desc')
						->select();
					foreach($member_list as $value){
						$member_t = strtotime(date('Y-m-d',$value['t']));//获取帐号创建日期
						if($member_t >= $end){//当日还未创建此帐号，不需要统计数据
							continue;
						}
						$sel_ret = $this->Income_count($value['uid'],$value['level'],$value['proportion'],$start,$end,$sel_ret);
					}
				}
				
				$this->set_member_bills($uid,$start,$proportion,$sel_ret);
				
				$ret['money'] += $sel_ret['money'];
				$ret['vip_money'] += $sel_ret['vip_money'];
				$ret['basic_money'] += $sel_ret['basic_money'];
				$ret['vip_success_num'] += $sel_ret['vip_success_num'];
				$ret['basic_success_num'] += $sel_ret['basic_success_num'];
				$ret['vip_fail_num'] += $sel_ret['vip_fail_num'];
				$ret['basic_fail_num'] += $sel_ret['basic_fail_num'];
				$ret['vip_success_number'] += $sel_ret['vip_success_number'];
				$ret['basic_success_number'] += $sel_ret['basic_success_number'];
				$ret['reg_user'] += $sel_ret['reg_user'];
				$ret['reg_woman_user'] += $sel_ret['reg_woman_user'];
				$ret['reg_man_user'] += $sel_ret['reg_man_user'];
				$ret['subscribe'] += $sel_ret['subscribe'];
				$ret['pay_user'] += $sel_ret['pay_user'];
				
			}else{//代理当日账单数据已存在 就不需要查询
				$ret = $ret_bills;
				$sel_ret = $ret_bills;
			}
			
			$time = time();
			$now_day=strtotime(date('Y-m-d'));
			
			if(($time-$now_day)<180 || (!empty($start) && $start==$now_day)){//凌晨3分前缓存数据只保留10秒
				$day_time = 10;
			}else{
				$day_time = 30*3600*24;
			}
			S('Income_count_'.$uid.'_'.$level.'_'.$start.'_'.$end,$sel_ret,$day_time);
		}else{
			$ret = $cache_Income_count;
		}
		return $ret;
	}
	/**
	* 查询代理当日账单
	**/
	function get_member_bills($uid,$start){
		$time = time();
		$now_day=strtotime(date('Y-m-d'));
		
		if($start == $now_day){//如果是查询当日数据 就跳出
			return false;
		}
		//获取代理当日的账单数据
		$where = [
				'refid'			=> $uid,
				'bills_date'	=> $start,
			];
		$bills = M('member_bills')->field('money,vip_money,basic_money,vip_success_num,basic_success_num,vip_fail_num,basic_fail_num,vip_success_number,basic_success_number,reg_user,reg_woman_user,reg_man_user,subscribe,pay_user')->where($where)->find();
		if(empty($bills)){
			return false;
		}
		return $bills;
	}
	/**
	* 添加代理当日的账单
	**/
	function set_member_bills($uid,$start,$proportion,$ret){
		$time = time();
		$now_day=strtotime(date('Y-m-d'));
		if($start >= $now_day){//如果是查询当日数据 就跳出
			return false;
		}
		$bills = $this->get_member_bills($uid,$start);
		if(!empty($bills)){//有数据时不再添加
			return false;
		}
		$ret['bills_date'] = $start;
		$ret['refid'] = $uid;
		$ret['proportion'] = $proportion;
		$ret['income'] = round($ret['money']*($proportion/100),2);
		$ret['status'] = 1;
		//开启事务
		M('member_bills')->startTrans();
		$bills_add = M('member_bills')->add($ret);
		$bills_total_money = true;
		$bills_money = true;
		//更新总充值金额
		if(!empty($ret['money'])){
			$bills_total_money = M('member')->where(['uid'=>$uid])->setInc('total_money',$ret['money']);
		}
		//更新未提现金额
		if(!empty($ret['income']) && $ret['income']!='0.00'){
			$member_data = [
								'money'=>['exp','`money`+'.$ret['income']],
								'total_income'=>['exp','`total_income`+'.$ret['income']],
							];
			$bills_money = M('member')->where(['uid'=>$uid])->save($member_data);
		}
		
		if ($bills_add && $bills_total_money && $bills_money) {//事务完成
			M('member_bills')->commit();
		} else {//回滚
			M('member_bills')->rollback();
		}
	}
	
	/**
	* 统计代理当日账单数据
	**/
	function Income_sel($uid,$start,$end){
		$where = [
					'refid'			=> $uid,
					//'status'		=> 1,
					'deduction'		=> 1,//是否扣量 1正常
				];
		if(!empty($start)){
			$where['request_time'][] = [
				'EGT',
				$start
			];
		}
		if(!empty($end)){
			$where['request_time'][] = [
				'LT',
				$end
			];
		}
		$ret = [
					'money'					=> 0,//充值总额
					'vip_money'				=> 0,//vip充值金额
					'basic_money'			=> 0,//普通充值金额
					'vip_success_num'		=> 0,//VIP充值成功订单数
					'basic_success_num'		=> 0,//普通充值成功订单数
					'vip_fail_num'			=> 0,//VIP充值失败订单数
					'basic_fail_num'		=> 0,//普通充值失败订单数
					'vip_success_number'	=> 0,//VIP充值成功人数
					'basic_success_number'	=> 0,//普通充值成功人数
					'reg_user'				=> 0,//总注册数
					'reg_woman_user'		=> 0,//注册女性
					'reg_man_user'			=> 0,//注册男性
					'subscribe'				=> 0,//关注数
					'pay_user'				=> 0,//支付人数
			];
		$ret_userrecharge = M('userrecharge')->field('money,status,uid,is_vip')->where($where)->select();
		
		$vip_user = [];
		$basic_user = [];
		foreach($ret_userrecharge as $value){
			if($value['is_vip'] ==2 ){//vip
				if($value['status'] == 1){//充值成功
					$ret['vip_money'] += $value['money'];
					$ret['money'] += $value['money'];
					$ret['vip_success_num'] ++;
					if(!isset($vip_user[$value['uid']])){
						$vip_user[$value['uid']]=$value['uid'];
					}
				}else{
					$ret['vip_fail_num'] ++;
				}
			}else{
				if($value['status'] == 1){//充值成功
					$ret['basic_money'] += $value['money'];
					$ret['money'] += $value['money'];
					$ret['basic_success_num'] ++;
					if(!isset($basic_user[$value['uid']])){
						$basic_user[$value['uid']]=$value['uid'];
					}
				}else{
					$ret['basic_fail_num'] ++;
				}
			}
		}	

		$ret['vip_success_number'] += count($vip_user);
		$ret['basic_success_number'] += count($basic_user);
		
		//获取User统计
		$where = [
					'refid'			=> $uid,
				];
		if(!empty($start)){
			$where['time'][] = [
				'EGT',
				$start
			];
		}
		if(!empty($end)){
			$where['time'][] = [
				'LT',
				$end
			];
		}
		$ret_user = M('user')->field('sex,subscribe,integral,uid')->where($where)->select();
		foreach($ret_user as $value){
			if($value['sex'] ==1 ){//vip
				$ret['reg_man_user']++;
			}else if($value['sex'] ==2){
				$ret['reg_woman_user']++;
			}
			if($value['subscribe'] ==1 ){
				$ret['subscribe']++;
			}
			$ret['reg_user']++;
		}
		$ret['pay_user'] +=$ret['vip_success_number']+$ret['basic_success_number'];
		return $ret;
	}
}
